"""
代码尝试专用脚本（空壳模板）
- 用于调试、测试新功能或片段
"""

import os
import time

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import scipy.stats
import seaborn as sns
from matplotlib.font_manager import FontProperties
from sklearn.covariance import GraphicalLasso, LedoitWolf
from sklearn.preprocessing import StandardScaler
from src.mgm import (
    add_age_group,
    bootstrap_diff,
    build_network_from_adj,
    compare_network_structure,
    draw_multi_year_agegroup_networks,
    draw_multi_year_networks,
    draw_network,
    draw_network_subplot,
    filter_vars,
    get_chinese_name,
    get_network_annotation,
    get_node_metrics,
    plot_density_heatmap,
    plot_happiness_centrality_bar,
    preprocess_data,
    run_ledoitwolf,
    run_mgm,
    save_and_show_fig,
    test_edge_weight_diff,
    test_node_centrality_diff,
)

from tqdm import tqdm
import yaml
import os
import pandas as pd

with open('config.yaml', encoding='utf-8') as f:
    config = yaml.safe_load(f)
csv_path = config.get('csv_path', 'data/CGSS三年.csv')
# 保证路径为项目根目录下的 data/CGSS三年.csv
csv_path = os.path.join(os.path.dirname(__file__), csv_path) if not os.path.isabs(csv_path) else csv_path
if not os.path.exists(csv_path):
    raise FileNotFoundError(f"数据文件不存在: {csv_path}")
df = pd.read_csv(csv_path)

with open(os.path.join(os.path.dirname(__file__), 'config.yaml'), encoding='utf-8') as f:
    config = yaml.safe_load(f)
CORE_NAME_MAP = config.get('core_name_map_mgm', {})

if __name__ == "__main__":
    print("=" * 40)
    start_time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    start_time = time.time()
    print(f"⏱ 代码尝试开始 {start_time_str}")
    print("=" * 40)

     # 参数集中管理
    params = {
        'csv_path': "CGSS三年.csv",
        'figures_dir': "figures",
        'fields_core': list(CORE_NAME_MAP.keys()),
        'control_vars': [
            "年龄", "教育程度",
            "个人实际年收入对数", "家庭实际人均收入对数",
            "高等教育标识", "工作强度标识","区县",
            "年份"
        ],
        'mgm_alpha': 0.05,
        'edge_threshold': 0.05,
        'unique_min': 2,
        'std_min': 1e-6
    }
    df = pd.read_csv(params['csv_path'], low_memory=False)
    df = df[df["城乡"].astype(str).str.strip() == "城市"].copy()
    missing_cols = [col for col in params['fields_core'] + params['control_vars'] if col not in df.columns]
    if missing_cols:
        print("缺失的列：", missing_cols)
    df_net = preprocess_data(df, params['fields_core'], params['control_vars'])
    df_net = add_age_group(df_net)  # 新增：添加年龄组

    end_time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    end_time = time.time()
    print("=" * 40)
    print(f"⌛️ 代码尝试结束 {end_time_str}")
    duration = end_time - start_time
    print(f"总耗时：{int(duration)} 秒（{duration/60:.2f} 分钟）")
    print("=" * 40)

